package com.inter.controller.newoutside;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.inter.entity.common.OrderPaymentManager;
import com.inter.entity.newinterentity.order.request.RequestOrderPackage;
import com.inter.entity.newinterentity.order.request.RequestOrderPackageData;
import com.inter.entity.newinterentity.order.request.RequestOrderPackageTradeData;
import com.inter.entity.newinterentity.order.response.ResponseOrderPackage;
import com.inter.entity.newinterentity.order.response.ResponseOrderPackageData;
import com.inter.entity.newinterentity.order.response.ResponseOrderPackageTradeData;
import com.inter.entity.interentity.utils.UtilsInterfacesPackage;
import com.inter.entity.pojo.Constant;
import com.inter.insideinterservice.newservice.TurnToOrderService;
import com.inter.service.OrderPaymentManagerService;
import com.inter.service.PartnerProductPackageService;
import com.inter.service.PartnerService;
import com.inter.service.SequenceService;
import com.inter.utils.MD5;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 下单 ：未使用！未使用！未使用！
 *
 * @author lm
 * @date 2018/12/20
 */
@RestController
@Api(description = "订购套餐")
public class OrderController {
    private static Logger logger = Logger.getLogger(OrderController.class);

    @Autowired
    private SequenceService sequenceService;
    @Autowired
    PartnerProductPackageService partnerProductPackageService;
    @Autowired
    OrderPaymentManagerService orderPaymentManagerService;
    @Autowired
    PartnerService partnerService;

    @CrossOrigin
    @RequestMapping(value = "order", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "下单", response = ResponseOrderPackage.class)
    public String order(@ApiParam @RequestBody RequestOrderPackage requestOrderPackage) {
        // 1，生成流水号
        String connSeqNo = sequenceService.getPackageTaskNo();
        // 2,生成当前时间戳
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String curtime = df.format(new Date());
        //3,定义要回复的内容
        String jsonString;
        UtilsInterfacesPackage utils = new UtilsInterfacesPackage();
        String requestStr = JSON.toJSONString(requestOrderPackage);

        if (StringUtils.isBlank(requestStr)) {
            logger.info("请求报文不合法:requestStr为空");
            jsonString = utils.dataWeiKong(connSeqNo, curtime);
            return jsonString;
        } else {
            logger.info("前端请求是：" + requestStr);
            RequestOrderPackage requestPackage = JSONArray.parseObject(requestStr, RequestOrderPackage.class);
            String requestSign = requestPackage.getSign();
            if (requestPackage.getSign() == null) {
                logger.info("请求报文不合法:sign为空");
                jsonString = utils.dataWeiKong(connSeqNo, curtime);
                return jsonString;
            } else {
                logger.info("请求的签名是：" + requestSign);
                RequestOrderPackageData requestData = requestPackage.getData();
                if (requestPackage.getData() == null) {
                    logger.info("请求报文不合法:data为空");
                    jsonString = utils.dataWeiKong(connSeqNo, curtime);
                    return jsonString;
                } else {
                    String partnerCode = requestData.getPartnerCode();
                    String partnerName = partnerProductPackageService.queryPartnerNameBypartnerCode(partnerCode);
                    String secret = partnerService.findSecretByPartnerCode(partnerCode);
                    logger.info("渠道名称：" + partnerName + ";密钥是：" + secret);
                    String ConnSeqNo = requestData.getConnSeqNo();
                    String tradeTime = requestData.getTradeTime();
                    String token = requestData.getToken();
                    String tradeType = requestData.getTradeType();
                    String lang = requestData.getLang();
                    RequestOrderPackageTradeData tradeData = requestData.getTradeData();

                    if (StringUtils.isBlank(partnerCode) || StringUtils.isBlank(ConnSeqNo) || StringUtils.isBlank(tradeTime) || StringUtils.isBlank(token) || StringUtils.isBlank(tradeType) || StringUtils.isBlank(lang) || tradeData == null) {
                        logger.info("请求报文不合法:data参数不合法");
                        jsonString = utils.dataWeiKong(connSeqNo, curtime);
                        return jsonString;
                    } else {
                        String deviceId = requestData.getTradeData().getDeviceId();
                        String globalOrder = requestData.getTradeData().getGlobalOrder();
                        String packageName = requestData.getTradeData().getPackageName();
                        String packageCode = requestData.getTradeData().getPackageCode();
                        //为了防止下单时上报的packageName是英文的，所以这边的packageName我们还是去数据库查出来比较好；
                        String name = partnerProductPackageService.queryPackageNameByCode(packageCode, partnerCode);
                        System.out.println("数据库取到的name是：" + name);
                        String packageType = requestData.getTradeData().getPackageType();
                        String orderPeriod = requestData.getTradeData().getOrderPeriod();
                        String amount = requestData.getTradeData().getAmount();
                        // String isOpen = requestData.getTradeData().getIsOpen();
                        String requestOrderId = requestData.getTradeData().getRequestOrderId();
                        String currencyCodeType = requestData.getTradeData().getCurrencyCodeType();


                        if (StringUtils.isBlank(deviceId) || StringUtils.isBlank(packageCode) || StringUtils.isBlank(name) || StringUtils.isBlank(packageType) ||
                                StringUtils.isBlank(orderPeriod) || StringUtils.isBlank(amount) || StringUtils.isBlank(requestOrderId) || StringUtils.isBlank(currencyCodeType)) {
                            logger.info("请求报文不合法:tradeData的值为null或者为空");
                            jsonString = utils.dataWeiKong(connSeqNo, curtime);
                            return jsonString;
                        } else {
                            // 将请求体json转成String
                            String str = JSON.toJSONString(requestData);
                            // 将Str拿去计算签名
                            String sign = utils.calculateSignature(str);
                            logger.info("计算的签名是：" + sign);
                            if (!requestSign.equalsIgnoreCase(sign)) {
                                logger.info("签名验证失败！");
                                jsonString = utils.publicMessage(ConnSeqNo, partnerCode, tradeTime, token, tradeType);
                                return jsonString;
                            } else {
                                //签名验证通过
                                //1,先存订单：先把拿到的数据存到数据库去
                                //还是需要判断一下数据库里面是不是已经有这条请求下单的记录了
                                int count = orderPaymentManagerService.findDataByRequestOrderId(requestOrderId, deviceId, orderPeriod, partnerCode, packageCode);

                                if (count <= 0) {
                                    OrderPaymentManager userOrder = new OrderPaymentManager();
                                    userOrder.setPartnerCode(partnerCode);
                                    userOrder.setPartnerName(partnerName);
                                    userOrder.setPackageCode(packageCode);
                                    userOrder.setPackageName(name);
                                    userOrder.setDeviceId(deviceId);
                                    //userOrder.setDeviceType(deviceType);
                                    userOrder.setPackageType(packageType);
                                    userOrder.setOrderPeriod(orderPeriod);
                                    userOrder.setAmount(amount);
                                    //默认的都是不开通
                                    userOrder.setIsOpen("0");
                                    userOrder.setGlobalOrder(globalOrder);
                                    userOrder.setRequestOrderId(requestOrderId);
                                    userOrder.setOrderCurrency(currencyCodeType);
                                    orderPaymentManagerService.storageOrderPayment(userOrder);
                                    logger.info("下单记录生成");

                                    //2:拿着现在有的数据去北北京下正式的单
                                    TurnToOrderService turnToOrderService = new TurnToOrderService();
                                    //userOrder = turnToOrderService.orderPackage(deviceId,deviceType, globalOrder, name, packageCode, packageType, orderPeriod, amount, secret, partnerCode);

                                    userOrder = turnToOrderService.orderPackage(deviceId, globalOrder, name, packageCode, packageType, orderPeriod, amount, secret, partnerCode);

                                    if (userOrder == null) {

                                        ResponseOrderPackageData data = new ResponseOrderPackageData();
                                        data.setConnSeqNo(ConnSeqNo);
                                        data.setPartnerCode(partnerCode);
                                        data.setToken(token);
                                        data.setTradeType(tradeType);
                                        data.setTradeTime(curtime);
                                        data.setTradeRstCode(Integer.parseInt(userOrder.getRetCode()));

                                        if ("en".equals(lang)) {
                                            if ("0022".equals(userOrder.getRetCode())) {
                                                //设备当前状态不允许订购流量套餐
                                                data.setTradeRstMessage("The current state of the device does not allow you to order a data plan");
                                            } else if ("0023".equals(userOrder.getRetCode())) {
                                                //不允许此合作伙伴的设备订购该流量套餐；
                                                data.setTradeRstMessage("This partner's device is not allowed to order the data package");
                                            } else if ("0024".equals(userOrder.getRetCode())) {
                                                //订购周期不合法，不能订购；
                                                data.setTradeRstMessage("The ordering period is illegal and cannot be ordered");
                                            } else if ("0025".equals(userOrder.getRetCode())) {
                                                //开通标识不合法，不能订购；
                                                data.setTradeRstMessage("Open the logo is not legal, can not order");
                                            } else if ("0009".equals(userOrder.getRetCode())) {
                                                //订购周期不合法，不能订购；
                                                data.setTradeRstMessage("No equipment");
                                            } else if ("0010".equals(userOrder.getRetCode())) {
                                                //开通标识不合法，不能订购；
                                                data.setTradeRstMessage("Device information does not exist");
                                            } else {
                                                data.setTradeRstMessage("fail");
                                            }
                                        } else {
                                            //中文的就不用翻译了，直接返回
                                            data.setTradeRstMessage(userOrder.getResultInfo());
                                        }

                                        ResponseOrderPackage responseOrder = new ResponseOrderPackage();
                                        responseOrder.setData(data);
                                        responseOrder.setSign(MD5.calcMD5(JSON.toJSONString(data)));
                                        // 返回给调用者的报文
                                        jsonString = JSON.toJSONString(responseOrder);
                                        logger.info("响应：" + jsonString);
                                        return jsonString;
                                    } else {
                                        if (true == Constant.RET_CODE_0000.equalsIgnoreCase(userOrder.getRetCode())) {
                                            //现在把拿到的orderId去数据库更新记录
                                            //1，先要判断当前用户之前有没有下过单，用调用方给的requestOrderId去做数据插入
                                            OrderPaymentManager user = new OrderPaymentManager();
                                            user.setRequestOrderId(requestOrderId);
                                            user.setDeviceId(deviceId);
                                            user.setPackageCode(packageCode);
                                            user.setPartnerCode(partnerCode);
                                            user.setOrderId(userOrder.getOrderId());
                                            user.setOrderStartDate(userOrder.getOrderStartDate());
                                            user.setOrderExpireDate(userOrder.getOrderExpireDate());
                                            orderPaymentManagerService.updateOrderIdByRequestOrderIdAndDeviceId(user);
                                            logger.info("拿回的订单更新：" + userOrder.getOrderId());

                                            //2,要准备回报的数据了
                                            List<ResponseOrderPackageTradeData> responseTradeData = new ArrayList<ResponseOrderPackageTradeData>();
                                            ResponseOrderPackageTradeData tra = new ResponseOrderPackageTradeData();
                                            tra.setOrderId(userOrder.getOrderId());
                                            tra.setOrderStartDate(userOrder.getOrderStartDate());
                                            tra.setOrderExpireDate(userOrder.getOrderExpireDate());
                                            responseTradeData.add(tra);

                                            ResponseOrderPackageData data = new ResponseOrderPackageData();
                                            data.setConnSeqNo(ConnSeqNo);
                                            data.setPartnerCode(partnerCode);
                                            data.setToken(token);
                                            data.setTradeTime(curtime);
                                            data.setTradeType(tradeType);
                                            data.setTradeRstCode(1000);
                                            data.setTradeRstMessage("success");
                                            data.setTradeData(responseTradeData);

                                            ResponseOrderPackage responseOrder = new ResponseOrderPackage();
                                            responseOrder.setData(data);
                                            responseOrder.setSign(MD5.calcMD5(JSON.toJSONString(data)));
                                            // 返回给调用者的报文
                                            jsonString = JSON.toJSONString(responseOrder);
                                            logger.info("响应报文：" + jsonString);
                                            return jsonString;

                                        } else {
                                            //就是返回码不是0000
                                            ResponseOrderPackageData data = new ResponseOrderPackageData();
                                            data.setConnSeqNo(ConnSeqNo);
                                            data.setPartnerCode(partnerCode);
                                            data.setToken(token);
                                            data.setTradeType(tradeType);
                                            data.setTradeTime(curtime);
                                            data.setTradeRstCode(Integer.parseInt(userOrder.getRetCode()));
                                            if (lang.equalsIgnoreCase("en")) {
                                                if ("0022".equals(userOrder.getRetCode())) {
                                                    //设备当前状态不允许订购流量套餐
                                                    data.setTradeRstMessage("The current state of the device does not allow you to order a data plan!");
                                                } else if ("0023".equals(userOrder.getRetCode())) {
                                                    //不允许此合作伙伴的设备订购该流量套餐；
                                                    data.setTradeRstMessage("This partner's device is not allowed to order the data package!");
                                                } else if ("0024".equals(userOrder.getRetCode())) {
                                                    //订购周期不合法，不能订购；
                                                    data.setTradeRstMessage("The ordering period is illegal and cannot be ordered!");
                                                } else if ("0025".equals(userOrder.getRetCode())) {
                                                    //开通标识不合法，不能订购；
                                                    data.setTradeRstMessage("Open the logo is not legal, can not order!");
                                                } else if ("0009".equals(userOrder.getRetCode())) {
                                                    //订购周期不合法，不能订购；
                                                    data.setTradeRstMessage("No equipment!");
                                                } else if ("0010".equals(userOrder.getRetCode())) {
                                                    //开通标识不合法，不能订购；
                                                    data.setTradeRstMessage("Device information does not exist!");
                                                } else {
                                                    data.setTradeRstMessage("fail!");
                                                }
                                            } else {//中文的就不用翻译了，直接返回
                                                data.setTradeRstMessage(userOrder.getResultInfo());
                                            }

                                            ResponseOrderPackage responseOrder = new ResponseOrderPackage();
                                            responseOrder.setData(data);
                                            responseOrder.setSign(MD5.calcMD5(JSON.toJSONString(data)));
                                            // 返回给调用者的报文
                                            jsonString = JSON.toJSONString(responseOrder);
                                            logger.info("响应报文：" + jsonString);
                                            return jsonString;
                                        }

                                    }

                                } else {
                                    //数据库里面已经有记录了就说明不要去重复请求单号了，直接回复重复请求！
                                    //走到这边说明重复请求相同的数据
                                    logger.info("重复请求！");
                                    jsonString = utils.duplicateRequestMessage(ConnSeqNo, partnerCode, tradeTime, token, tradeType);
                                    return jsonString;

                                }
                            }
                        }
                    }
                }
            }

        }
    }
}
